package com.zxl.grocery.microservice.auth.server.interceptor;

import com.zxl.grocery.microservice.auth.server.configuration.ClientConfiguration;
import com.zxl.grocery.microservice.auth.server.service.AuthClientService;
import com.zxl.grocery.microservice.common.context.BaseContextHandler;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;

/**
 * @Author: zxl
 * @Description: 该拦截器主要用于服务端向鉴权系统申请token ；如果服务与服务之间用@FeignClient请求时，请求前会先走这里申请一个token；
 * @Date: Created in 23:38 2017/10/24
 * @Modified By:
 */
public class ClientTokenInterceptor implements RequestInterceptor {
    private Logger logger = LoggerFactory.getLogger(ClientTokenInterceptor.class);
    @Autowired
    private ClientConfiguration clientConfiguration;
    @Autowired
    private AuthClientService authClientService;
    @Value("${jwt.token-header}")
    private String tokenHeader;
    @Override
    public void apply(RequestTemplate requestTemplate) {
        try {
            //加一个包装，把当前服务的token放入请求头里面
            requestTemplate.header(clientConfiguration.getClientTokenHeader(), authClientService.apply(clientConfiguration.getClientId(), clientConfiguration.getClientSecret()));
            if( StringUtils.isNoneBlank(BaseContextHandler.getToken()) ){
                requestTemplate.header(tokenHeader, BaseContextHandler.getToken());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
